package com.webserver.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * WebServer是一个模拟Tomcat的web容器，实现了Tomcat的基础功能
 */
public class WebServerApplication {
    /*
       该类对象记录的是启动WebServer项目的那个类,用这个类作为靶点,
       以便于寻找controller
       比如:MyFirstWebApp项目中的Boot类,在那个类的main方法中调用了
           WebServerApplication的run方法启动的WebServer,那么这个Boot
           类就是靶点类,我们将来扫描controller包是就要求这个包必须放在
           Boot类所在的包中

     */
    public static Class TARGET;

    private ServerSocket serverSocket;
    private ExecutorService threadPool;



    public WebServerApplication(){
        try {
            System.out.println("正在启动服务端...");
            serverSocket = new ServerSocket(8088);
            threadPool = Executors.newFixedThreadPool(50);
            System.out.println("服务端启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while(true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了!");
                //启动一个线程处理该客户端交互
                ClientHandler handler = new ClientHandler(socket);
                threadPool.execute(handler);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void run(Class target, String[] args) {
        TARGET = target;
        WebServerApplication application = new WebServerApplication();
        application.start();
    }
}
